package approve.action;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;

import model.pojo.Employee;
import models.dao.AcEliManagerDao;
import models.dao.LoginSystem;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

public class LogoutActivity extends Activity{
	EditText username,pass,dbname;
	CheckBox rememberMeCbx;
	Button btLogin;
	TextView lbdbname,t,t2,tvwaiting;
	LayoutInflater inflaterwaiting;
	View textEntryViewwaiting;
	AlertDialog.Builder builderwaiting;
	AlertDialog alertwaiting;
	ImageView imageVN,imageEN,imageKR;
	int kt=0;
	private final Handler uiHandler=new Handler();
	private boolean isUpdateRequired=false;
	AcEliManagerDao acelidao= new AcEliManagerDao();
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		try{
			initall();
		}catch(Exception e){
			e.printStackTrace();
			Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage( getBaseContext().getPackageName() );
			i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(i);
		}
	}
	
	private void initall(){
		LoginActivity.flagruntimer=true;
		LoginActivity.soluong=0;
		LoginActivity.emp= new Employee();
		MainEApproval.mNotificationManager.cancel(MainEApproval.SIMPLE_NOTFICATION_ID);
		MainEApproval.timer.cancel();
		
		setContentView(R.layout.login);
		init();
		loadlable();
		readFile();
		this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		imageVN.setOnClickListener(processImageVN);
		imageEN.setOnClickListener(processImageEN);
		imageKR.setOnClickListener(processImageKR);
		btLogin.setOnClickListener(loginbtn);
	}
	
	
	private OnClickListener loginbtn = new OnClickListener() {
		public void onClick(View v) {
//			btLogin.setBackgroundResource(R.drawable.bt_general_pressed);
			if(!username.getText().toString().equals("null") && !pass.getText().toString().equals("null") && !dbname.getText().toString().equals("null") && !username.getText().toString().equals("") && !pass.getText().toString().equals("") && !dbname.getText().toString().equals("")){
				alertwaiting.show();
				try{
					new Thread(){
						public void run() {
							if(acelidao.checkexitdb(dbname.getText().toString())==true){
								LoginActivity.database=dbname.getText().toString();
								LoginActivity.emp = new LoginSystem().checkLogin(username.getText().toString(), pass.getText().toString(),LoginActivity.database);
								if (LoginActivity.emp != null) {
									if(rememberMeCbx.isChecked()==true){
										try{
											FileOutputStream file = openFileOutput("user.txt", Context.MODE_PRIVATE);
											file.write(LoginActivity.database.getBytes());
											file.write("-".getBytes());
											file.write(LoginActivity.emp.getUserName().getBytes());
											file.write("-".getBytes());
											file.write(pass.getText().toString().getBytes());
											file.close();
										}catch(Exception e){
											e.printStackTrace();
										}
									}else{
										try{
											FileOutputStream file = openFileOutput("user.txt", Context.MODE_PRIVATE);
											file.write("null".getBytes());
											file.write("-".getBytes());
											file.write("null".getBytes());
											file.write("-".getBytes());
											file.write("null".getBytes());
											file.close();
										}catch(Exception e){
											e.printStackTrace();
										}
									}
								} 
								else {
									kt=1;
								}
							}else{
								kt=2;
							}
							uiHandler.post( new Runnable(){
								@Override
								public void run() {
									if(isUpdateRequired){
									}else{
										switch (kt) {
										case 0:
											startActivity();
											alertwaiting.cancel();
											break;
										case 1:
											alertwaiting.cancel();
											openDialogError();
											break;
										case 2:
											alertwaiting.cancel();
											openDialogNoDB();
										default:
											break;
										}
									}
								}
							} );
						}
					}.start();
				}catch (Exception e) {}
			}
		}
	}; 

	private void startActivity() {
		Intent i = new Intent(LogoutActivity.this, MainEApproval.class);
		startActivity(i);
		finish();
	}
	private void openDialogError() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Warning");
		builder.setMessage(LoginActivity.lang.getString("ac_tb_UserOrPassNotCorrect"));
		builder.setCancelable(false);
		builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
//				btLogin.setBackgroundResource(R.drawable.bt_general_normal);
				kt=0;
			}
		});
		builder.show();
	}

	private void openDialogNoDB() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Warning");
		builder.setMessage(LoginActivity.lang.getString("ac_CSDLKhongTonTai"));
		builder.setCancelable(false);
		builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
//				btLogin.setBackgroundResource(R.drawable.bt_general_normal);
				kt=0;
			}
		});
		builder.show();
	}

	private void init(){
		btLogin = (Button) findViewById(R.id.btLogin);
		dbname=(EditText)findViewById(R.id.tv_dbname);
		username = (EditText) findViewById(R.id.userName);
		pass = (EditText) findViewById(R.id.pass);
		rememberMeCbx = (CheckBox)findViewById(R.id.checkRemember);
		lbdbname=(TextView) findViewById(R.id.lb_dbname);
		t = (TextView) findViewById(R.id.tendn);
		t2 = (TextView) findViewById(R.id.matkhau);
		inflaterwaiting = (LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);          
		textEntryViewwaiting = inflaterwaiting.inflate(R.layout.waiting, null);
		tvwaiting=(TextView)textEntryViewwaiting.findViewById(R.id.TextView01);					
		builderwaiting = new AlertDialog.Builder(LogoutActivity.this);
		builderwaiting.setView(textEntryViewwaiting);
		builderwaiting.setCancelable(false);
		alertwaiting = builderwaiting.create();
		imageVN = (ImageView)findViewById(R.id.imageViewVN);
		imageEN = (ImageView)findViewById(R.id.imageViewUK);
		imageKR = (ImageView)findViewById(R.id.imageViewKR);
	}
	public void loadlable() {
		tvwaiting.setText(LoginActivity.lang.getString("waiting")+"...");
		lbdbname.setText(LoginActivity.lang.getString("ac_ma_DatabaseName"));
		t.setText(LoginActivity.lang.getString("ac_ma_UserName"));
		t2.setText(LoginActivity.lang.getString("ac_ma_Password"));
		btLogin.setText(LoginActivity.lang.getString("ac_login"));
		rememberMeCbx.setText(LoginActivity.lang.getString("rememberlogin"));
		rememberMeCbx.setChecked(true);
	}

	public OnClickListener processImageVN = new OnClickListener() {
		@Override
		public void onClick(View arg0) {
			LoginActivity.typeLang = "VN";
			LoginActivity.lang=LoginActivity.alllangs.getBundle(LoginActivity.typeLang);
			loadlable();
			try{
				writeLanguageFile();
			}catch (Exception e) {
			}
		}
	};

	public OnClickListener processImageEN = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			LoginActivity.typeLang = "EN";
			LoginActivity.lang=LoginActivity.alllangs.getBundle(LoginActivity.typeLang);
			loadlable();
			try{
				writeLanguageFile();
			}catch (Exception e) {
			}
		}
	};

	public OnClickListener processImageKR = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			LoginActivity.typeLang = "KR";
			LoginActivity.lang=LoginActivity.alllangs.getBundle(LoginActivity.typeLang);
			loadlable();
			try{
				writeLanguageFile();
			}catch (Exception e) {
			}
		}
	};

	private void readFile(){
		try {
			FileInputStream fr = openFileInput("user.txt");
			Scanner scanner = new Scanner(fr);
			scanner.useDelimiter("-");
			dbname.setText(scanner.next().trim());
			username.setText(scanner.next().trim());
			pass.setText("");
			if(dbname.getText().toString().equals("") || dbname.getText().toString().equals("null")){
				dbname.setText("");
			}			
			if(username.getText().toString().equals("") || username.getText().toString().equals("null")){
				username.setText("");
			}			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void writeLanguageFile() throws Exception{
		FileOutputStream file = openFileOutput("language.txt", Context.MODE_PRIVATE);
		file.write(LoginActivity.typeLang.getBytes());
		file.close();
	}
	
	@Override
	public void onBackPressed() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(LoginActivity.lang.getString("exitapp"));
		builder.setMessage(LoginActivity.lang.getString("questionexitapp"));
		builder.setPositiveButton(LoginActivity.lang.getString("ok"),new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				LogoutActivity.this.moveTaskToBack(true);
				android.os.Process.killProcess(android.os.Process.myPid());
				android.os.Process.sendSignal(android.os.Process.myPid(), android.os.Process.SIGNAL_KILL);
			}
		});
		
		builder.setNegativeButton(LoginActivity.lang.getString("cancel"), new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
			}
		});
		AlertDialog alertDialog = builder.create();
		alertDialog.show();
	}
}